package first.group.ssh.packet;

import first.group.ssh.SSHConsts;
import first.group.ssh.packet.reader.IntegerReader;
import first.group.ssh.packet.reader.StringReader;
import first.group.ssh.packet.writer.StringWriter;
import java.nio.ByteBuffer;

public class ChannelExtendedDataPacket extends Packet {

    public final int recipientChannel;
    public final int dataTypeCode;
    public final byte[] data;

    public ChannelExtendedDataPacket(int recipientChannel, int dataTypeCode, byte[] data) {
        super(SSHConsts.SSH_MSG_CHANNEL_EXTENDED_DATA);
        this.recipientChannel = recipientChannel;
        this.dataTypeCode = dataTypeCode;
        this.data = data;
    }

    public static PacketParser<ChannelExtendedDataPacket> PARSER = new ChannelExtendedDataPacket.Parser();

    private static class Parser extends PacketParser<ChannelExtendedDataPacket> {

        @Override
        public ChannelExtendedDataPacket parse(ByteBuffer buffer) {
            var recipientChannel = IntegerReader.readInteger(buffer);
            if (recipientChannel == null) {
                return null;
            }
            var dataTypeCode = IntegerReader.readInteger(buffer);
            if (dataTypeCode == null) {
                return null;
            }
            var data = StringReader.readByteArray(buffer);
            if (data == null) {
                return null;
            }
            return new ChannelExtendedDataPacket(recipientChannel, dataTypeCode, data);
        }
    }

    @Override
    public void write(ByteBuffer buffer) {
        buffer.putInt(recipientChannel);
        buffer.putInt(dataTypeCode);
        StringWriter.writeByteArray(buffer, data);
    }
}
